﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Management;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace NetWorkSet
{
    class SetHelper
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc;

        /// <summary>
        /// 获取本机IP/掩码/网关地址
        /// </summary>
        /// <returns></returns>
        public string[] GetLocalAddress(string nicName, string parameter)
        {
            moc = mc.GetInstances();
            string[] addresses = new string[4];
            foreach (ManagementObject mo in moc)
            {
                if (Convert.ToBoolean(mo["ipEnabled"]))
                {
                    if (mo["Caption"].Equals(nicName))
                    {
                        if (((string[])mo[parameter]) == null)
                        {
                            if (addresses[0] == null)
                            {
                                addresses[0] = "";
                                addresses[1] = "";
                                addresses[2] = "";
                                addresses[3] = "";
                                return addresses;
                            }
                        }
                        addresses = ((string[])mo[parameter])[0].ToString().Split('.');
                    }
                }  
            }
            return addresses;
        }

        /// <summary>
        /// 获取网卡名称(显示）
        /// </summary>
        /// <returns></returns>
        public string[] GetNicNameShow()
        {
            moc = mc.GetInstances();
            string[] addresses = new string[moc.Count];
            int len = 0;
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;
                addresses[len++] = mo["Caption"].ToString();
            }
            string str = "";
            for (int i = 0; i < addresses.Length; i++)
            {
                if (addresses[i] != null)
                    str += addresses[i].Substring(11, addresses[i].Length - 11) + ".";
            }
            if (str.Length!=0)
            {
                str = str.Substring(0, str.Length - 1);                  
            }
            else
            {
                //MessageBox.Show("没有读取到网卡信息", "提示");
            }
            string[] strAddersses = str.Split('.');
            //返回网卡名称
            return strAddersses;
        }

        /// <summary>
        /// 获取网卡名称(不显示）
        /// </summary>
        /// <returns></returns>
        public string[] GetNicName()
        {
            moc = mc.GetInstances();
            string[] addresses = new string[moc.Count];
            int len = 0;
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;
                addresses[len++] = mo["Caption"].ToString();
            }
            string str = "";
            for (int i = 0; i < addresses.Length; i++)
            {
                if (addresses[i] != null)
                    str += addresses[i] + ".";
            }
            if (str.Length != 0)
            {
                str = str.Substring(0, str.Length - 1);
            }
            else
            {
                //MessageBox.Show("没有读取到网卡信息", "提示");
            }
            string[] strAddersses = str.Split('.');
            //返回网卡名称
            return strAddersses;
        }

        /// <summary>
        /// 设置DNS
        /// </summary>
        /// <param name="dns"></param>
        public void SetDNS(string nicName, string[] dns)
        {
            SetIPAddress(nicName, null, null, null, dns);
        }
        /// <summary>
        /// 设置网关
        /// </summary>
        /// <param name="getway"></param>
        public void SetGetWay(string nicName, string getway)
        {
            SetIPAddress(nicName, null, null, new string[] { getway }, null);
        }
        /// <summary>
        /// 设置网关
        /// </summary>
        /// <param name="getway"></param>
        public void SetGetWay(string nicName, string[] getway)
        {
            SetIPAddress(nicName, null, null, getway, null);
        }
        /// <summary>
        /// 设置IP地址和掩码
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        public void SetIPAddress(string nicName, string ip, string submask)
        {
            SetIPAddress(nicName, new string[] { ip }, new string[] { submask }, null, null);
        }
        /// <summary>
        /// 设置IP地址，掩码和网关
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        /// <param name="getway"></param>
        public void SetIPAddress(string nicName, string ip, string submask, string getway)
        {
            SetIPAddress(nicName, new string[] { ip }, new string[] { submask }, new string[] { getway }, null);
        }
        /// <summary>
        /// 设置IP地址，掩码，网关和DNS
        /// </summary>
        /// <param name="nicName">网卡名</param>
        /// <param name="ip">IP</param>
        /// <param name="submask">掩码</param>
        /// <param name="getway">网关</param>
        /// <param name="dns">DNS</param>
        public void SetIPAddress(string nicName, string[] ip, string[] submask, string[] getway, string[] dns)
        {
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            foreach (ManagementObject mo in moc)
            {
                //如果没有启用IP设置的网络设备则跳过
                if (!(bool)mo["IPEnabled"])
                    continue;
                if (mo["Caption"].Equals(nicName))
                {
                    //设置IP地址和掩码
                    if (ip != null && submask != null)
                    {
                        inPar = mo.GetMethodParameters("EnableStatic");
                        inPar["IPAddress"] = ip;
                        inPar["SubnetMask"] = submask;
                        outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                    }
                    //设置网关地址
                    if (getway != null)
                    {
                        inPar = mo.GetMethodParameters("SetGateways");
                        inPar["DefaultIPGateway"] = getway;
                        outPar = mo.InvokeMethod("SetGateways", inPar, null);
                    }
                    //设置DNS地址
                    if (dns != null)
                    {
                        inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        inPar["DNSServerSearchOrder"] = dns;
                        outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                    }

                    break;
                }
            }
        }
        /// <summary>
        /// 启用DHCP服务器
        /// </summary>
        public void EnableDHCP()
        {
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                //如果没有启用IP设置的网络设备则跳过
                if (!(bool)mo["IPEnabled"])
                    continue;
                //重置DNS为空
                mo.InvokeMethod("SetDNSServerSearchOrder", null);
                //开启DHCP
                mo.InvokeMethod("EnableDHCP", null);
            }
        }
        /// <summary>
        /// 判断是否IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool IsIPAddress(string ip)
        {
            string[] arr = ip.Split('.');
            if (arr.Length != 4)
                return false;
            string pattern = @"\d{1,3}";
            for (int i = 0; i < arr.Length; i++)
            {
                string d = arr[i];
                if (i == 0 && d == "0")
                    return false;
                if (!Regex.IsMatch(d, pattern))
                    return false;
                if (d != "0")
                {
                    d = d.TrimStart('0');
                    if (d == "")
                        return false;
                    if (int.Parse(d) > 255)
                        return false;
                }
            }
            return true;
        }


        /// <summary>
        /// 将IP设置为自动获取
        /// </summary>
        public void setIPAuto()
        {
            string _doscmd = "netsh interface ip set address 本地连接 DHCP";
            Process pro = new Process();
            pro.StartInfo.FileName = "cmd.exe";
            pro.StartInfo.UseShellExecute = false;
            pro.StartInfo.RedirectStandardInput = true;
            pro.StartInfo.RedirectStandardOutput = true;
            pro.StartInfo.RedirectStandardError = true;
            pro.StartInfo.CreateNoWindow = true;
            pro.Start();
            pro.StandardInput.WriteLine(_doscmd.ToString());
            pro.StandardInput.WriteLine("exit");
        }

        /// <summary>
        /// 将DNS设置为自动获取
        /// </summary>
        public void SetDNSAuto()
        {
            string _doscmd = "netsh interface ip set dns 本地连接 DHCP";
            Process pro = new Process();
            pro.StartInfo.FileName = "cmd.exe";
            pro.StartInfo.UseShellExecute = false;
            pro.StartInfo.RedirectStandardInput = true;
            pro.StartInfo.RedirectStandardOutput = true;
            pro.StartInfo.RedirectStandardError = true;
            pro.StartInfo.CreateNoWindow = true;
            pro.Start();
            pro.StandardInput.WriteLine(_doscmd.ToString());
            pro.StandardInput.WriteLine("exit");
        }

        public void YesOrNo()
        {

        }

        ///// <summary>
        ///// 设置IP地址，掩码，网关等
        ///// </summary>
        //public void setIPaddress()
        //{
        //    string _ipaddress = "192.168.1.107";
        //    string _submask = "255.255.255.0";
        //    string _gateway = "192.168.1.1";
        //    string _dns1 = "202.96.69.38";

        //    string _doscmd = "netsh interface ip set address 本地连接 static " + _ipaddress + " " + _submask + " " + _gateway + " 1";
        //    Process p = new Process();
        //    p.StartInfo.FileName = "cmd.exe";
        //    p.StartInfo.UseShellExecute = false;
        //    p.StartInfo.RedirectStandardInput = true;
        //    p.StartInfo.RedirectStandardOutput = true;
        //    p.StartInfo.RedirectStandardError = true;
        //    p.StartInfo.CreateNoWindow = true;
        //    p.Start();
        //    p.StandardInput.WriteLine(_doscmd.ToString());
        //    _doscmd = "netsh interface ip set dns 本地连接 static " + _dns1;
        //    p.StandardInput.WriteLine(_doscmd.ToString());

        //    p.StandardInput.WriteLine("exit");
        //}


        /// <summary>
        /// Set IP for the specified network card name
        /// </summary>
        /// <PARAM name="nicName">Caption of the network card</PARAM>
        /// <PARAM name="IpAddresses">Comma delimited string 
        ///           containing one or more IP</PARAM>
        /// <PARAM name="SubnetMask">Subnet mask</PARAM>
        /// <PARAM name="Gateway">Gateway IP</PARAM>
        /// <PARAM name="DnsSearchOrder">Comma delimited DNS IP</PARAM>
        public void SetIP(string nicName, string IpAddresses, string SubnetMask, string Gateway, string DnsSearchOrder)
        {
            foreach (ManagementObject mo in moc)
            {
                // Make sure this is a IP enabled device. 
                // Not something like memory card or VM Ware
                if (Convert.ToBoolean(mo["IPEnabled"]))
                {
                    if (mo["Caption"].Equals(nicName))
                    {

                        ManagementBaseObject newIP =
                          mo.GetMethodParameters("EnableStatic");
                        ManagementBaseObject newGate =
                          mo.GetMethodParameters("SetGateways");
                        ManagementBaseObject newDNS =
                          mo.GetMethodParameters("SetDNSServerSearchOrder");

                        newGate["DefaultIPGateway"] = new string[] { Gateway };
                        newGate["GatewayCostMetric"] = new int[] { 1 };

                        newIP["IPAddress"] = IpAddresses.Split(',');
                        newIP["SubnetMask"] = new string[] { SubnetMask };

                        newDNS["DNSServerSearchOrder"] = DnsSearchOrder.Split(',');

                        ManagementBaseObject setIP = mo.InvokeMethod(
                          "EnableStatic", newIP, null);
                        ManagementBaseObject setGateways = mo.InvokeMethod(
                          "SetGateways", newGate, null);
                        ManagementBaseObject setDNS = mo.InvokeMethod(
                          "SetDNSServerSearchOrder", newDNS, null);

                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Returns the network card configuration of the specified NIC
        /// </summary>
        /// <PARAM name="nicName">Name of the NIC</PARAM>
        /// <PARAM name="ipAdresses">Array of IP</PARAM>
        /// <PARAM name="subnets">Array of subnet masks</PARAM>
        /// <PARAM name="gateways">Array of gateways</PARAM>
        /// <PARAM name="dnses">Array of DNS IP</PARAM>
        public string[] GetIP(string nicName)
        {
            string[] Str = new string[4];
            foreach (ManagementObject mo in moc)
            {
                // Make sure this is a IP enabled device. 
                // Not something like memory card or VM Ware
                if (Convert.ToBoolean(mo["ipEnabled"]))
                {
                    if (mo["Caption"].Equals(nicName))
                    {
                        Str[0] = ((string[])mo["IPAddress"])[0].ToString();
                        Str[1] = ((string[])mo["IPSubnet"])[0].ToString();
                        Str[2] = ((string[])mo["DefaultIPGateway"])[0].ToString();
                        Str[3] = ((string[])mo["DNSServerSearchOrder"])[0].ToString();
                        break;
                    }
                }
            }
            return Str;
        }

        public string GetIpStr(string nicName)
        {
            string[] Str= this.GetIP(nicName);
            

            return Str[0] + "." + Str[1] + "." + Str[2] + "." + Str[3];

        }
        ///
        ///将字符串IP转换为数组IP
        ///
        public string[] toArray(string str)
        {
            string[] Str = str.Split('.');
            return Str;
        }
    }
}
